local p = {}

local function _parseCSVLine (line,sep) 
	local res = {}
	local pos = 1
	sep = sep or ','
	while true do 
		local c = string.sub(line,pos,pos)
		if (c == "") then break end
		if (c == '"') then
			-- quoted value (ignore separator within)
			local txt = ""
			repeat
				local startp,endp = string.find(line,'^%b""',pos)
				txt = txt..string.sub(line,startp+1,endp-1)
				pos = endp + 1
				c = string.sub(line,pos,pos) 
				if (c == '"') then txt = txt..'"' end 
				-- check first char AFTER quoted string, if it is another
				-- quoted string without separator, then append it
				-- this is the way to "escape" the quote char in a quote. example:
				--   value1,"blub""blip""boing",value3  will result in blub"blip"boing  for the middle
			until (c ~= '"')
			--print("-------------txt: " .. txt)
			table.insert(res,txt)
			assert(c == sep or c == "")
			pos = pos + 1
		else	
			-- no quotes used, just look for the first separator
			local startp,endp = string.find(line,sep,pos)
			if (startp) then 
				table.insert(res,string.sub(line,pos,startp-1))
				pos = endp + 1
			else
				-- no separator found -> use rest of string and terminate
				table.insert(res,string.sub(line,pos))
				break
			end 
		end
	end
	return res
end

function p.load(filename)
    local path = filename  --TODO
    local data = io.readfile(path)
	local lineStr = string.split(data, '\n')

	local titles = string.split(lineStr[2], ",")
	local types = string.split(lineStr[3], ",")

	local function checkTyp(value, index)
		local t = types[index]
		if t=="int" or t=="i" then 
			return checkint(value)
		elseif t == "double" or t=="d" then 
			return checknumber(value)
		end 
		return value 
	end 

	local arrs = {}
	for i=4, #lineStr-1, 1 do 
		-- print(lineStr[i])
		local content = _parseCSVLine(lineStr[i]) 
--		local id = checkint(content[1])
        local id = tostring(content[1]) -- zzh add 20170207
		arrs[id] = {};  
        for j = 1, #titles, 1 do  
            arrs[id][titles[j]] = checkTyp(content[j], j);  
        end  
	end 
	return arrs 
end

return p
